package com.youlu.campus.admin.community.service.impl;

import com.youlu.campus.admin.base.BaseService;
import com.youlu.campus.admin.community.dto.*;
import com.youlu.campus.admin.community.entity.ArticleInfo;
import com.youlu.campus.admin.community.service.ArticleService;
import com.youlu.campus.admin.utils.JsonUtil;
import com.youlu.campus.base.base.GeneraStatusEnum;
import com.youlu.campus.base.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 文章信息接口实现类
 * @author: YangJ
 * @date: 2020/11/24 18:15
 */
@Slf4j
@Service("articleService")
public class ArticleServiceImpl extends BaseService implements ArticleService {

    @Override
    public boolean createArticle(ArticleCreateRequest request) {
        log.info("新增文章信息开始，参数:{}", JsonUtil.toJSON(request));

        ArticleInfo articleInfo = mapperFacade.map(request, ArticleInfo.class);
        articleInfo.setStatus(GeneraStatusEnum.ON.getCode());
        articleInfo.setCreatorId(request.getUserId());
        mongoTemplate.insert(articleInfo);

        log.info("新增文章信息结束");
        return true;
    }

    @Override
    public boolean updateArticle(ArticleUpdateRequest request) {
        log.info("修改文章信息开始，参数:{}", JsonUtil.toJSON(request));

        ArticleInfo articleInfo = findOne(request.getId());
        mapperFacade.map(request,articleInfo);
        articleInfo.setUpdatedTime(new Date());
        mongoTemplate.save(articleInfo);

        log.info("修改文章信息结束");
        return true;
    }

    @Override
    public boolean deleteArticle(String id) {
        log.info("删除文章信息开始，id:{}", id);

        ArticleInfo articleInfo = findOne(id);
        articleInfo.setDeleted(true);
        articleInfo.setUpdatedTime(new Date());
        mongoTemplate.save(articleInfo);

        log.info("删除文章信息结束");
        return true;
    }

    @Override
    public Page<ArticleListResponse> articleList(ArticleQueryRequest request) {
        log.info("查询文章信息列表，参数:{}", JsonUtil.toJSON(request));

        Query query = new Query();
        if(StringUtils.isNotBlank(request.getTitle())){
            Pattern pattern = Pattern.compile("^.*" + request.getTitle() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("title").regex(pattern));
        }
        if(StringUtils.isNotBlank(request.getStatus())){
            query.addCriteria(Criteria.where("status").is(request.getStatus()));
        }

        query.addCriteria(Criteria.where("deleted").is(false));
        long count = mongoTemplate.count(query, ArticleInfo.class);

        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
        if(StringUtils.isNotBlank(request.getSortDir()) &&
                StringUtils.isNotBlank(request.getSortVal()) ){
//            query.with(new Sort(Sort.Direction.fromString(request.getSortDir()), request.getSortVal()));
        }else {
//            query.with(new Sort(Sort.Direction.DESC, "createdTime"));
            Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
            query.with(sort);
        }
        List<ArticleInfo> articleInfos = mongoTemplate.find(query.with(pageRequest), ArticleInfo.class);
        List<ArticleListResponse> list = articleInfos.stream().map(articleInfo -> {
            ArticleListResponse response = mapperFacade.map(articleInfo, ArticleListResponse.class);
            return response;
        }).collect(Collectors.toList());
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    @Override
    public ArticleResponse query(String id) {
        log.info("查询文章信息开始，id:{}", id);

        ArticleInfo articleInfo = findOne(id);
        ArticleResponse response = mapperFacade.map(articleInfo, ArticleResponse.class);

        log.info("查询文章信息结束");
        return response;
    }

    @Override
    public boolean updateArticleStatus(String id, String status) {
        log.info("修改文章信息状态开始，id:{},status:{}", id,status);

        ArticleInfo articleInfo = findOne(id);
        articleInfo.setStatus(status);
        articleInfo.setUpdatedTime(new Date());

        mongoTemplate.save(articleInfo);

        log.info("修改文章信息状态结束");
        return true;
    }

    @Override
    public boolean updateWeight(WeightRequest request) {
        log.info("修改文章权重开始，参数:{}", JsonUtil.toJSON(request));

        ArticleInfo articleInfo = findOne(request.getId());
        articleInfo.setWeight(request.getWeight());
        articleInfo.setUpdatedTime(new Date());
        mongoTemplate.save(articleInfo);

        log.info("修改文章权重结束");
        return true;
    }


    private ArticleInfo findOne(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        ArticleInfo articleInfo = mongoTemplate.findOne(query, ArticleInfo.class);
        if(articleInfo == null){
            throw new BusinessException("文章信息查询失败!");
        }
        return articleInfo;
    }
}
